﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Threading;
using System.Net.Http;
using System.Threading.Tasks;
using Autofac.Core.Lifetime;
using Autofac;

namespace MgSoft.K3Cloud.WebApi
{
    public class KingdeeHttpClientHelper
    {
        public ILifetimeScope LifetimeScope { get; set; }

        /// <summary>
        /// Cookie，保证登录后，所有访问持有一个Cookie；
        /// </summary>
        public CookieContainer Cookie { get; private set; } = new CookieContainer();

        /// <summary>
        /// HTTP访问
        /// </summary>
        public string SysncRequest(string url, string content) => SysncRequest(url, content, CancellationToken.None);


        /// <summary>
        /// HTTP访问
        /// </summary>
        public string SysncRequest(string url, string content, CancellationToken cancellationToken)
        {
            var result = SysncRequestDo(url, content, cancellationToken);

            return result.GetAwaiter().GetResult();
        }


        private async Task<string> SysncRequestDo(string url, string content, CancellationToken cancellationToken)
        {
            var handler = new HttpClientHandler() { UseCookies = true };
            handler.CookieContainer = Cookie;
            HttpClient httpClient = LifetimeScope.Resolve<HttpClient>(new NamedParameter("handler", handler));
            //httpClient.Timeout = TimeSpan.FromSeconds(300);
            try
            {
                //ThreadPool.GetAvailableThreads(out int workerThreads, out int completionPortThreads);
                //Debug.WriteLine($@"workerThreads : {workerThreads} | completionPortThreads : {completionPortThreads} ");

                JObject jObj = new JObject();
                jObj.Add("format", 1);
                jObj.Add("useragent", "ApiClient");
                jObj.Add("rid", Guid.NewGuid().ToString().GetHashCode().ToString());
                jObj.Add("parameters", content);
                jObj.Add("timestamp", DateTime.Now);
                jObj.Add("v", "1.0");
                string sContent = jObj.ToString();

                StringContent httpContent = new StringContent(sContent, Encoding.UTF8, "application/json");
                var responseMessage = await httpClient.PostAsync(new Uri(url), httpContent, cancellationToken);
                var result = await responseMessage.Content.ReadAsStringAsync();
                return ValidateResult(result);
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested)
                    throw new TimeoutException($@"超出等待时间,终止请求");
                throw ex;
            }
        }






        private static string ValidateResult(string responseText)
        {
            if (responseText.StartsWith("response_error:"))
            {
                var failText = responseText.TrimStart("response_error:".ToCharArray());
            }
            return responseText;
        }
    }
}